﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mengsk.ProxyDelivery.Service
{
    public class ServiceContainer
    {
        public static string ServerAddress = null;

        public static string AccessToken { get; set; }

        static List<object> services = new List<object>();

        static ServiceContainer()
        {
            Type[] types = typeof(ServiceContainer).Assembly.GetTypes();

            foreach (Type t in types)
            {
                if (t.BaseType != null && t.BaseType.FullName.Contains("ServiceBase"))
                {
                    services.Add(Activator.CreateInstance(t));
                }
            }
        }

        public static T GetService<T>() where T : IUrl
        {
            object obj = services.FirstOrDefault(o => o.GetType() == typeof(T) || o.GetType().GetInterface(typeof(T).Name, true) != null);

            //设置URL
            if (obj == null)
            {
                throw new Exception("未找到指定的服务类型");
            }
            (obj as IUrl).BaseUrl = ServerAddress;
            return (T)obj;
        }
    }
}
